import { __projectDir as proj } from "albert.gao/node";
import ChildProcess, { exec } from "child_process";
import { Router } from "express";
import Fs from "fs-extra";
import Path from "path";
import filesToCopy from "~/shared/files-to-copy";

const router = Router();

/** 新建一个project */
router.use("/api/create-project", async (req, res) => {
  let {
    body: { path },
  } = req;
  let data = await createAnotherProject(path);
  res.json(data);
});

/** yarn一个project */
router.use("/api/create-project-yarn", async (req, res) => {
  let {
    body: { path },
  } = req;
  let ps1Path = Path.resolve(path, "install.cmd");
  Fs.writeFileSync(ps1Path, "yarn", {
    encoding: "utf8",
  });
  // open(ps1Path, {});
  await new Promise((resolve) => {
    exec(`yarn`, { cwd: path }, resolve).stdout?.pipe(process.stdout);
  });
  res.status(200).end();
});

/**
 * 在某个路径复制当前项目的有效文件
 * @param newProjPath 该目录的路径
 * @returns 返回ElMessage的选项
 */
async function createAnotherProject(newProjPath: string): Promise<{
  type: string;
  // @ts-ignore
  message: any;
}> {
  try {
    // eslint-disable-next-line no-unused-vars
    await new Promise((resolve, _reject) => {
      let child = ChildProcess.fork(
        Path.resolve(__dirname, "@/child-process/empty-dir.js")
      );
      // @ts-ignore
      child.on("message", ({ type }) => {
        if (type === "success") {
          child.kill();
          resolve(1);
        }
      });
      child.send({ path: newProjPath });
    });

    Fs.emptyDirSync(newProjPath);
    for (let relPath of filesToCopy) {
      try {
        Fs.copySync(
          Path.resolve(proj, relPath),
          Path.resolve(newProjPath, relPath),
          {
            overwrite: true,
          }
        );
      } catch (error) {
        console.log(error);
      }
    }
    return {
      type: "success",
      // @ts-ignore
      message: "Project created successfully!",
    };
  } catch (Error) {
    console.error(Error);
    return {
      type: "error",
      // @ts-ignore
      message: Error.message,
    };
  }
}

export default router;
